import { formatGMTDate, compareObject, compareObject2 } from '../../../../assets/js/util.js'
import details from './datils.vue'
import advance from './advancedFilter.vue'
import echarts from 'echarts'
export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            //菜单索引
            navDefault: '0',
            // title
            title: "实时概况",
            xlsxTitle: '',
            /* 的宽*/
            pageWidth: '100%',
            // 选择的时间
            date: '',
            // 选择日期的前一天
            dateBefore: '',
            // 对比时间
            cdate: '',
            // 对比日期的前时间
            cdateBefore: '',
            // details 展示数据
            datas: [],
            // 渠道数组
            channels: [],
            // 服务器数组
            servers: [],
            // 请求的参数
            //
            postObj: {
                'date': '2017-05-25',
                'cdate': '2017-05-24',
                'platformid': '0',
                'channelid': '0',
                'serverid': '0'
            },
            // 整体实时在线
            real: {
                color: ['#2eb398', '#9d79d8', '#f9af3f'],
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    top: '10px',
                    data: ['', '', '']
                },
                grid: {
                    left: '0%',
                    right: '1%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: [],
                    axisLabel: {
                        interval: 10,
                        rotate: 45, //倾斜度 -90 至 90 默认为0
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: '1',
                    type: 'line',
                    showSymbol: false,
                    data: []
                }, {
                    name: '2',
                    type: 'line',
                    showSymbol: false,
                    data: []
                }, {
                    name: '3',
                    type: 'line',
                    showSymbol: false,
                    data: []
                }]
            },
            // 实时数据显示
            realLoadShow: true,
            // 表格数据
            tableData: [],
            tabelHead: [
                { prop: "hour", label: "日期" },
                { prop: "newUserLookValue", label: "新增账号数-查看日期" },
                { prop: "newUserCompareValue", label: "新增账号数-对比日期" },
                { prop: "userSecond2LeftHourLookValue", label: "累计实时次留-查看日期" },
                { prop: "userSecond2LeftHourCompareValue", label: "累计实时次留-对比日期" },
                { prop: "payLookValue", label: "付费金额(" + localStorage.getItem("ZULONGBICURRENCY") + ")-查看日期" },
                { prop: "payCompareValue", label: "付费金额(" + localStorage.getItem("ZULONGBICURRENCY") + ")-对比日期" }
            ],
            // 分小时数据 付费金额
            pay: {
                color: ['#2eb398', '#9d79d8', '#f9af3f'],
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    top: '10px',
                    data: [{
                        name: '',
                    }, {
                        name: '',
                    }, {
                        name: '',
                    }]
                },
                grid: {
                    left: '0%',
                    right: '1%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: [],
                    axisLabel: {
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: '1',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'circle'
                }, {
                    name: '2',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'roundRect'
                }, {
                    name: '3',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'triangle'
                }]
            },
            // 点击查看分小时详细数据 表格数据
            tableData2: [],
            tabelHead2: [
                { prop: "hour", label: "日期" },
                { prop: "newUserLookValue", label: "新增账号数-查看日期" },
                { prop: "newUserCompareValue", label: "新增账号数-对比日期" },
                { prop: "payUserLookValue", label: "付费账号数-查看日期" },
                { prop: "payUserCompareValue", label: "付费账号数-对比日期" },
                { prop: "payLookValue", label: "付费金额(" + localStorage.getItem("ZULONGBICURRENCY") + ")-查看日期" },
                { prop: "payCompareValue", label: "付费金额(" + localStorage.getItem("ZULONGBICURRENCY") + ")-对比日期" },
                { prop: "newPayUserLookValue", label: "新增账号付费人数-查看日期" },
                { prop: "newPayUserCompareValue", label: "新增账号付费人数-对比日期" },
                { prop: "newUserPayLookValue", label: "新增账号付费金额(" + localStorage.getItem("ZULONGBICURRENCY") + ")-查看日期" },
                { prop: "newUserPayCompareValue", label: "新增账号付费金额(" + localStorage.getItem("ZULONGBICURRENCY") + ")-对比日期" },
            ],
        }
    },
    methods: {
        // 设置图表初始化宽度
        chartsWidth(el) {
            if (document.getElementById(el) !== null) {
                document.getElementById(el).style.width = window.innerWidth - 290 + "px";
            }
        },
        //初始化
        _init() {
            var arr = ['newAccount', 'payMoney', 'activeAccount', 'account', 'id', 'pay', 'person', 'money'];
            for (var x = 0; x < arr.length; x++) {
                this.chartsWidth(arr[x]);
                this[arr[x] + 'Charts'] = echarts.init(document.getElementById(arr[x]));
                this[arr[x] + 'Charts'].setOption(this.pay);
            }
            window.addEventListener('resize', function() {
                for (var i in arr) {
                    this.chartsWidth(arr[i])
                }
                var resizeArr = ['realTimeDataChart', 'newAccountCharts', 'payMoneyCharts', 'activeAccountCharts', 'accountCharts', 'idCharts', 'payCharts', 'personCharts', 'moneyCharts']
                for (var j in resizeArr) {
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        // 选择时间
        dateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择查看时间！')
            } else {
                this.date = val;
                /**
                 * 设置选择日期的前一天
                 */
                var dateBeforeStr = val.replace(/-/g, '/');
                this.dateBefore = formatGMTDate(new Date(dateBeforeStr) - 86400000, true);
                this.postObj.date = val;
            }
            if (this.tableData.length > 0) {
                this.getData(this.postObj);
            }
        },
        // 对比时间
        cdateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择对比时间！')
            } else {
                this.cdate = val;
                /**
                 * 设置对比日期的前一天
                 */
                var dateBeforeStr = val.replace(/-/g, '/');
                this.cdateBefore = formatGMTDate(new Date(dateBeforeStr) - 86400000, true);
                this.postObj.cdate = val;
            }
            if (this.tableData.length > 0) {
                this.getData(this.postObj);
            }
        },
        // 选择游戏的平台
        handleSelect(key, keyPath) {
            if (key === '4') {
                this.$refs.advance.filterShow = true;
            } else {
                this.postObj['platformid'] = key;
                this.postObj['serverid'] = '0';
                this.postObj['channelid'] = '0';
                this.getData(this.postObj);
            }
        },
        // 内容框的排序
        detailsSort(data) {
            this.datas = data.sort(compareObject2('title', true));
        },
        // 获取后台数据
        getData(data) {
            var that = this;
            var p = new Promise(function(resolve, reject) {
                that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`, {
                    params: { 'ps': `date=${data.date}&cdate=${data.cdate}&platformid=${data.platformid}&channelid=${data.channelid}&serverid=${data.serverid}` }
                }).then(function(res) {
                    resolve(res.body)
                })
            })
            p.then(function(value) {
                var data = JSON.parse(value)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data["res"]) === 0) {
                    that.detailsSort(data["datas"]);
                    that.echartsData(data);
                    that.tableConfig(data['detailDatas1']);
                    that.tableConfig2(data['detailDatas']);
                } else {

                    /*if(data['res'] === '2'){
                    	that.$router.push('/main/err401')
                    	// that.$route.path('main/err401')
                    }*/
                    // that.errorFun(data['res']);
                }
            })
        },
        // 获取服务器list 平台list  服务器list
        getList() {
            var that = this;
            var pushData = function(pushArr, attr, data) {
                that[pushArr] = [];
                for (var i in data[attr]) {
                    that[pushArr].push({
                        value: i,
                        label: data[attr][i]
                    })
                }
            };
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "initParam",
                    ps: ""
                }
            }).then(function(res) {
                var data = JSON.parse(res.body)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\}\}\"/g, '\}\}'));
                if (parseInt(data["res"]) === 0) {
                    // 后台select的数据
                    var lists = ["platformItmes", "channelItmes", "serverItmes"];
                    // 页面select名字
                    var nameLists = ["plats", "channels", "servers"];
                    for (var i = 0; i < lists.length; i++) {
                        if (data[lists[i]] !== undefined) {
                            pushData(nameLists[i], lists[i], data);
                        }
                    }
                } else {
                    this.getErrorMsg(Number(data.res))
                }
            })
        },
        // 改变表数据
        echartsData(d) {
            this.realLoadShow = false;
            // 删除零的元素
            function removeZero(arr) {
                // console.log(arr)
                var date = new Date();
                if (arr === undefined) {
                    return;
                } else if (arr.length > 25) {
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i] === 0 && i > date.getHours() * 11) {
                            arr[i] = '-'
                        }
                    }
                } else {
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i] === 0 && i > date.getHours()) {
                            arr[i] = '-'
                        }
                    }
                }
                return arr;
            }
            // 实时数据获取到数据渲染
            if (d.onlineRealTimeChart === undefined) {
                var data = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data = d['onlineRealTimeChart']['jsonStr'];
            }
            this.realTimeDataChart.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data.columnkeys
                },
                series: [{
                        name: data.names[0],
                        data: removeZero(data.data[0])
                    },
                    {
                        name: data.names[1],
                        data: removeZero(data.data[1])
                    },
                    {
                        name: data.names[2],
                        data: removeZero(data.data[2])
                    }
                ]
            });

            //  分小时累计数据 新增账号数获取到数据渲染
            var account = d['lineChart21']['jsonStr'];
            //  将数字转换为日期
            function dateStr(arr) {
                var arrN = [];
                for (var i = 0; i < arr.length; i++) {
                    if (i < 10) {
                        var date = '0' + arr[i] + ':00';
                    } else {
                        var date = arr[i] + ':00';
                    }
                    arrN.push(date)
                }
                return arrN;
            }
            this.newAccountCharts.setOption({
                legend: {
                    data: account.names
                },
                xAxis: {
                    data: dateStr(account.columnkeys)
                },
                series: [{
                        name: account.names[0],
                        data: removeZero(account.data[0])
                    },
                    {
                        name: account.names[1],
                        data: account.data[1]
                    },
                    {
                        name: account.names[2],
                        data: account.data[2]
                    }
                ]
            });

            // 分小时累计数据 付费金额(￥)获取到数据渲染
            var payMoney = d['lineChart51']['jsonStr'];
            this.payMoneyCharts.setOption({
                legend: {
                    data: payMoney.names
                },
                xAxis: {
                    data: dateStr(payMoney.columnkeys)
                },
                series: [{
                        name: payMoney.names[0],
                        data: removeZero(payMoney.data[0])
                    },
                    {
                        name: payMoney.names[1],
                        data: payMoney.data[1]
                    },
                    {
                        name: payMoney.names[2],
                        data: payMoney.data[2]
                    }
                ]
            });

            // 分小时活跃数据 获取到数据渲染
            var activeAccount = d['lineChart81']['jsonStr'];
            this.activeAccountCharts.setOption({
                legend: {
                    data: activeAccount.names
                },
                xAxis: {
                    data: dateStr(activeAccount.columnkeys)
                },
                series: [{
                        name: activeAccount.names[0],
                        data: removeZero(activeAccount.data[0])
                    },
                    {
                        name: activeAccount.names[1],
                        data: activeAccount.data[1]
                    },
                    {
                        name: activeAccount.names[2],
                        data: activeAccount.data[2]
                    }
                ]
            });

            //分小时数据  新增账号数 获取到数据渲染
            var acc = d['lineChart2']['jsonStr'];
            this.accountCharts.setOption({
                legend: {
                    data: acc.names
                },
                xAxis: {
                    data: dateStr(acc.columnkeys)
                },
                series: [{
                        name: acc.names[0],
                        data: removeZero(acc.data[0])
                    },
                    {
                        name: acc.names[1],
                        data: acc.data[1]
                    },
                    {
                        name: acc.names[2],
                        data: acc.data[2]
                    }
                ]
            });

            //分小时数据  付费账号数 获取到数据渲染
            var id = d['lineChart4']['jsonStr'];
            this.idCharts.setOption({
                legend: {
                    data: id.names
                },
                xAxis: {
                    data: dateStr(id.columnkeys)
                },
                series: [{
                        name: id.names[0],
                        data: removeZero(id.data[0])
                    },
                    {
                        name: id.names[1],
                        data: id.data[1]
                    },
                    {
                        name: id.names[2],
                        data: id.data[2]
                    }
                ]
            });

            //分小时数据  付费金额 获取到数据渲染
            var pay = d['lineChart5']['jsonStr'];
            this.payCharts.setOption({
                legend: {
                    data: pay.names
                },
                xAxis: {
                    data: dateStr(pay.columnkeys)
                },
                series: [{
                        name: pay.names[0],
                        data: removeZero(pay.data[0])
                    },
                    {
                        name: pay.names[1],
                        data: pay.data[1]
                    },
                    {
                        name: pay.names[2],
                        data: pay.data[2]
                    }
                ]
            });

            //分小时数据  新增账号付费人数 获取到数据渲染
            var person = d['lineChart6']['jsonStr'];
            this.personCharts.setOption({
                legend: {
                    data: person.names
                },
                xAxis: {
                    data: dateStr(person.columnkeys)
                },
                series: [{
                        name: person.names[0],
                        data: removeZero(person.data[0])
                    },
                    {
                        name: person.names[1],
                        data: person.data[1]
                    },
                    {
                        name: person.names[2],
                        data: person.data[2]
                    }
                ]
            });

            //分小时数据  新增账号付费人数 获取到数据渲染
            var money = d['lineChart7']['jsonStr'];
            this.moneyCharts.setOption({
                legend: {
                    data: money.names
                },
                xAxis: {
                    data: dateStr(money.columnkeys)
                },
                series: [{
                        name: money.names[0],
                        data: removeZero(money.data[0])
                    },
                    {
                        name: money.names[1],
                        data: money.data[1]
                    },
                    {
                        name: money.names[2],
                        data: money.data[2]
                    }
                ]
            });
        },
        //表格数据时间优化
        tableConfig(data) {
            for (var i in data) {
                if (i < 10) {
                    data[i]['hour'] = '0' + data[i]['hour'] + ':00 ~ ' + '0' + data[i]['hour'] + ":59";
                } else {
                    data[i]['hour'] = data[i]['hour'] + ':00 ~ ' + data[i]['hour'] + ":59";
                }
                data[i]["userSecond2LeftHourCompareValue"] = (data[i]["userSecond2LeftHourCompareValue"] * 100).toFixed(2);
                data[i]["userSecond2LeftHourLookValue"] = (data[i]["userSecond2LeftHourLookValue"] * 100).toFixed(2);
            }
            this.tableData = data;
        },
        //点击查看分小时详细数据 表格数据时间优化
        tableConfig2(data) {
            for (var i in data) {
                if (i < 10) {
                    data[i]['hour'] = '0' + data[i]['hour'] + ':00 ~ ' + '0' + data[i]['hour'] + ":59";
                } else {
                    data[i]['hour'] = data[i]['hour'] + ':00 ~ ' + data[i]['hour'] + ":59";
                }
            }
            this.tableData2 = data;
        },
        // 每隔15秒一次
        setTimeOnline() {
            var that = this;
            setInterval(function() {
                if (that.$route.path === '/main/realTime/realTimeData') {
                    that.getData(that.postObj);
                }
            }, 15000);
        },
        // 表格下载
        excel(tableIndex, sheet) {
            var that = this;
            that.xlsxTitle = sheet + "-" + that.postObj.date + "对比" + that.postObj.cdate;
            that.downloadExl(that['tabelHead' + tableIndex], that['tableData' + tableIndex], that.xlsxTitle, sheet);
        }
    },
    components: {
        'v-details': details,
        'v-advance': advance,
    },
    computed: {
        // xlsx(){
        //   return this.title+'.xlsx'
        // }
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        // 初始化时间
        this.date = new Date();
        this.dateBefore = formatGMTDate(new Date(new Date().getTime() - 86400000), true)
        this.cdate = new Date(new Date().getTime() - 86400000);
        this.cdateBefore = formatGMTDate(new Date(new Date().getTime() - (2 * 86400000)), true)
        this.postObj.date = formatGMTDate(new Date(), true);
        this.postObj.cdate = formatGMTDate(new Date().getTime() - 86400000, true);

        // 获取到服务器 平台 渠道 list
        this.getList();

        // 实时数据
        this.realTimeDataChart = echarts.init(document.getElementById('realTimeData'));
        this.realTimeDataChart.setOption(this.real);
        this._init();
        this.getData(this.postObj);

        setTimeout(this.setTimeOnline, 15000);
    },
    beforeCreate() {
        this.currency = localStorage.getItem('ZULONGBICURRENCY');
    }
}